// 该页面为微博列表页面，已归类到 weibo 目录
<script setup lang="ts">
  import { page, push, remove, top } from '@/api/weibo.ts'
  import { WeiboPageParam, Weibo } from '@/types'
  import TableCustom from '@/components/common/TableCustom.vue'
  import TableSearch from '@/components/common/TableSearch.vue'
  import WeiboEdit from '@/views/weibo/WeiboEdit.vue'
  import WeiboCard from '@/views/weibo/components/WeiboCard.vue'
  import { FormOption, TableColumns } from '@/types/form-option.ts'
  import {
    CirclePlusFilled,
    Delete,
    Edit,
    Finished,
    Picture,
    Top,
    Menu,
    Grid,
  } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { onMounted, reactive, ref, computed } from 'vue'

  const searchOpt = ref<FormOption[]>([{ type: 'input', label: '关键字：', prop: 'keyword' }])

  // 表格字段配置
  const columns = ref<TableColumns[]>([
    { type: 'index', prop: '', label: '序号', width: 55, align: 'center' },
    { prop: 'content', label: '内容' },
    { prop: 'createTime', label: '创建时间' },
    { prop: 'status', label: '状态', width: 100 },
    { prop: 'topFlag', label: '置顶标记', width: 100 },
    { prop: 'operator', label: '操作', width: 600 },
  ])

  const param = reactive<WeiboPageParam>({
    keyword: '',
    pageNum: 1,
    pageSize: 10,
  })

  // 视图模式：table-表格模式，card-卡片模式
  const viewMode = ref<'table' | 'card'>('card')

  const visible = ref(false)
  const isEdit = ref(false)
  const rowData = ref()
  //表格数据
  const tableData = ref<Weibo[]>([])
  //总数
  const total = ref(0)

  // 图片预览相关
  const previewDialogVisible = ref(false)
  const currentPreviewWeibo = ref<Weibo | null>(null)
  const previewImageUrls = computed(() => {
    if (!currentPreviewWeibo.value || !currentPreviewWeibo.value.files) {
      return []
    }
    return currentPreviewWeibo.value.files.map(file => file.url)
  })

  const handlePreviewImages = (weibo: Weibo) => {
    if (weibo.files && weibo.files.length > 0) {
      currentPreviewWeibo.value = weibo
      previewDialogVisible.value = true
    } else {
      ElMessage.info('没有可预览的图片')
    }
  }

  //搜索方法
  const handleSearch = () => {
    changePage(1)
  }

  const handleAdd = () => {
    rowData.value = {}
    visible.value = true
    isEdit.value = true
  }

  const handleEdit = (row: Weibo) => {
    rowData.value = { ...row }
    visible.value = true
    isEdit.value = true
  }

  const handleChangeStatus = async (row: Weibo) => {
    await push({ id: row.id, status: row.status === 1 ? 0 : 1 })
    ElMessage.success(row.status === 1 ? '已下架' : '已发布')
    await getData()
  }

  const handleDelete = async (row: Weibo) => {
    await remove({ id: row.id })
    ElMessage.success('删除成功')
    await getData()
  }
  const handleTop = async (row: Weibo) => {
    await top({ id: row.id, topFlag: row.topFlag === 1 ? 0 : 1 })
    ElMessage.success('修改成功')
    await getData()
  }

  const changePage = (val: number) => {
    param.pageNum = val
    getData()
  }

  //查询分页
  const getData = async () => {
    const data = await page(param)
    tableData.value = data.records
    total.value = data.total
  }

  const closeDialog = () => {
    visible.value = false
    isEdit.value = false
    console.log(2)
    getData()
  }

  // 切换视图模式
  const toggleViewMode = () => {
    viewMode.value = viewMode.value === 'table' ? 'card' : 'table'
  }

  onMounted(() => {
    getData()
  })
</script>

<template>
  <div>
    <!--  搜索栏  -->
    <TableSearch :query="param" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        </div>
        <el-button
          type="primary"
          :icon="viewMode === 'table' ? Grid : Menu"
          @click="toggleViewMode"
        >
          {{ viewMode === 'table' ? '卡片视图' : '表格视图' }}
        </el-button>
      </div>

      <!-- 表格视图 -->
      <TableCustom
        v-if="viewMode === 'table'"
        :columns="columns"
        :table-data="tableData"
        :total="total"
        :del-func="handleDelete"
        :current-page="param.pageNum"
        :page-size="param.pageSize"
        :edit-func="handleEdit"
        :change-page="changePage"
      >
        <template #content="{ row }">
          <el-tooltip effect="light">
            <template #content>
              <span style="max-width: 500px">{{ row.content }}</span>
            </template>
            <span>{{ row.content }}</span>
          </el-tooltip>
        </template>
        <template #status="{ row }">
          <el-tag v-if="row.status == 1" type="success">已发布</el-tag>
          <el-tag v-else type="info">未发布</el-tag>
        </template>
        <template #topFlag="{ row }">
          <el-tag v-if="row.topFlag == 1" type="success">置顶</el-tag>
          <el-tag v-else type="info">未置顶</el-tag>
        </template>
        <template #operator="{ row }">
          <el-button
            type="primary"
            :icon="Picture"
            size="small"
            :disabled="!row.files || row.files.length === 0"
            @click="handlePreviewImages(row)"
          >
            预览
          </el-button>
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="warning" size="small" :icon="Finished" @click="handleChangeStatus(row)">
            {{ row.status === 1 ? '下架' : '发布' }}
          </el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
            删除
          </el-button>
          <el-button type="success" size="small" :icon="Top" @click="handleTop(row)">
            {{ row.topFlag === 1 ? '取消置顶' : '置顶' }}
          </el-button>
        </template>
      </TableCustom>

      <!-- 卡片视图 -->
      <div v-else class="weibo-cards-container">
        <WeiboCard
          v-for="weibo in tableData"
          :key="weibo.id"
          :weibo="weibo"
          @edit="handleEdit"
          @delete="handleDelete"
          @change-status="handleChangeStatus"
          @top="handleTop"
        />

        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="param.pageNum"
            :page-size="param.pageSize"
            :total="total"
            layout="prev, pager, next, jumper"
            background
            @current-change="changePage"
          />
        </div>
      </div>
    </div>

    <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑' : '新增'"
      destroy-on-close
      :show-close="false"
    >
      <template #header>
        <div class="dialog-header">
          <el-page-header @back="closeDialog" />
        </div>
      </template>
      <WeiboEdit :data="rowData" :is-edit="isEdit" :close="closeDialog" />
    </el-dialog>

    <!-- 朋友圈风格的图片预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="微博详情"
      :append-to-body="true"
      width="700px"
      destroy-on-close
      class="weibo-preview-dialog"
    >
      <div v-if="currentPreviewWeibo" class="weibo-preview-container">
        <!-- 微博内容 -->
        <div class="weibo-preview-content">{{ currentPreviewWeibo.content }}</div>

        <!-- 图片网格 -->
        <div class="weibo-preview-images">
          <div
            v-for="(file, index) in currentPreviewWeibo.files"
            :key="file.id"
            class="preview-image-item"
          >
            <el-image
              :src="file.url"
              fit="cover"
              :preview-src-list="previewImageUrls"
              :initial-index="index"
              :hide-on-click-modal="true"
            />
          </div>
        </div>

        <!-- 状态信息 -->
        <div class="weibo-preview-status">
          <el-tag v-if="currentPreviewWeibo.status == 1" type="success" size="small">已发布</el-tag>
          <el-tag v-else type="info" size="small">未发布</el-tag>
          <el-tag v-if="currentPreviewWeibo.topFlag == 1" type="success" size="small" class="ml-10">
            置顶
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .dialog-header {
    margin: 5px;
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
  }

  .weibo-cards-container {
    display: flex;
    flex-direction: column;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    margin-bottom: 20px;
  }

  /* 朋友圈风格的微博预览样式 */
  .weibo-preview-container {
    padding: 16px;
  }

  .weibo-preview-content {
    font-size: 15px;
    line-height: 1.6;
    color: #333;
    margin-bottom: 16px;
    white-space: pre-wrap;
    word-break: break-all;
  }

  .weibo-preview-images {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin-bottom: 16px;
  }

  .preview-image-item {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
  }

  .preview-image-item .el-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .weibo-preview-status {
    display: flex;
    margin-top: 10px;
    align-items: center;
  }

  .ml-10 {
    margin-left: 10px;
  }

  /* 预览对话框样式 */
  :deep(.weibo-preview-dialog .el-dialog__body) {
    padding: 0;
  }
</style>
